0192. 统计词频【中等】
1. 📝 题目描述
写一个 bash 脚本以统计一个文本文件 words.txt 中每个单词出现的频率。
单词 x 在文本文件中出现的次数称作该单词的 频率。
为了简单起见,你可以假设:
words.txt只包括小写字母和' '。- 每个单词只由小写字母组成。
- 单词间由一个或多个空格字符分隔。
示例:
假设 words.txt 内容如下:
txt
the day is sunny the the
the sunny is is1
2
2
你的脚本应当输出(以词频降序排列):
txt
the 4
is 3
sunny 2
day 11
2
3
4
2
3
4
说明:
- 不要担心词频相同的单词的排序问题,每个单词出现的频率都是唯一的。
- 你可以使用一行 Unix pipes 实现吗?
2. 🎯 s.1 - 管道命令
c
// Shell 题目,使用 Bash 实现
// cat words.txt | tr -s ' ' '\n' | sort | uniq -c | sort -rn | awk '{print $2, $1}'1
2
2
js
// Shell 题目,使用 Bash 实现
// cat words.txt | tr -s ' ' '\n' | sort | uniq -c | sort -rn | awk '{print $2, $1}'1
2
2
py
# Shell 题目,使用 Bash 实现
# cat words.txt | tr -s ' ' '\n' | sort | uniq -c | sort -rn | awk '{print $2, $1}'1
2
2
- 时间复杂度:
,主要来自排序 - 空间复杂度:
,存储所有单词
算法思路:
- 这是一道 Shell 题目,使用管道命令组合实现
tr -s ' ' '\n'将空格替换为换行符,每行一个单词sort | uniq -c统计每个单词出现次数sort -rn按频率降序排列,awk调整输出格式